package main

import (
	"flag"
	"fmt"
	"github.com/zeromicro/go-zero/core/conf"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/rest"
	"go-zero-project/common/global"
	"go-zero-project/common/limit"
	"go-zero-project/common/middleware"
	"go-zero-project/services/user/api/internal/config"
	"go-zero-project/services/user/api/internal/handler"
	initXxl "go-zero-project/services/user/api/internal/handler/xxl"
	"go-zero-project/services/user/api/internal/initialize/mq/consumer"
	"go-zero-project/services/user/api/internal/initialize/nacos"
	"go-zero-project/services/user/api/internal/svc"
	"os"
)

//  swagger go install github.com/zeromicro/goctl-swagger@latest
//  goctl api plugin -plugin goctl-swagger="swagger -filename user.json" -api user.api -dir .

func main() {
	flag.Parse()
	// 1.根据环境变量读取不同配置文件
	configPath := "services/user/api/etc/user-center-api-%s.yaml"
	configEnv := os.Getenv(global.GoENV)
	if len(configEnv) < 1 {
		configEnv = global.DefaultEnv
	}
	configPath = fmt.Sprintf(configPath, configEnv)
	configFile := flag.String("f", configPath, "the config file")
	logx.Infof(" read %s file profile:%s ...", configPath, configEnv)
	var c config.Config
	// 2.加载配置文件
	conf.MustLoad(*configFile, &c)
	// 3.加载内置依赖组件
	server := rest.MustNewServer(c.RestConf)
	defer server.Stop()
	// 4.设置ServiceContext
	ctx := svc.NewServiceContext(c)
	// 5.注册路由
	handler.RegisterHandlers(server, ctx)
	// 6.注册中心 注册
	nacos.RegisterNacos(c)
	// 7.注册定时任务
	initXxl.RegisterTask(ctx)
	// 8.init consumer
	initConsumer := consumer.InitConsumer(c.MqConf, ctx)
	if initConsumer != nil {
		logx.Error(initConsumer)
	}
	// 9.全局限流中间件
	periodLimit := limit.NewPeriodLimit(c.Limit.Period, c.Limit.Quota, ctx.RedisClient, global.PeriodLimitPrefix)
	rateMiddleware := middleware.NewLimitRateMiddleware(periodLimit, ctx.Config.Name)
	server.Use(rateMiddleware.Handle)
	// 9.jwt 中间件
	authMiddleware := middleware.NewJwtAuthMiddleware(c.JwtConf.AccessSecret, c.JwtConf.IgnoreUrl)
	server.Use(authMiddleware.Handle)
	logx.Infof("Starting server at %s:%d...\n", c.Host, c.Port)
	server.Start()
}
